package com.isoft.service.impl;

import com.isoft.entity.DfmeOnreEntity;
import com.isoft.mapper.DfmeOnreMapper;
import com.isoft.service.DfmeOnreService;
import com.isoft.util.XmlParserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Service
public class DfmeOnreServiceImpl implements DfmeOnreService {
    private static final Logger logger = LoggerFactory.getLogger(DfmeOnreServiceImpl.class);

    @Autowired
    private DfmeOnreMapper dfmeOnreMapper;

    @Autowired
    private XmlParserUtil xmlParserUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(MultipartFile file) throws IOException {
        String xmlContent = new String(file.getBytes(), StandardCharsets.UTF_8);
        logger.info("Processing DFME-ONRE XML file: {}, size: {} bytes",
                file.getOriginalFilename(), file.getSize());
        return parseAndSave(xmlContent);
    }

    @Override
    public void parseAndSave(DfmeOnreEntity entity) {
        processOnreData(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String parseAndSave(String xmlContent) {
        try {
            if (xmlContent == null || xmlContent.trim().isEmpty()) {
                throw new IllegalArgumentException("XML content is empty");
            }

            DfmeOnreEntity entity = xmlParserUtil.parseXml(xmlContent, DfmeOnreEntity.class);

            if (entity == null || entity.getDflt() == null) {
                throw new IllegalArgumentException("Invalid DFME-ONRE XML structure");
            }

            processOnreData(entity);

            return "DFME-ONRE data processed successfully. Flight ID: " + entity.getDflt().getFlightId();
        } catch (Exception e) {
            logger.error("DFME-ONRE XML processing failed", e);
            throw new RuntimeException("Failed to process DFME-ONRE XML: " + e.getMessage());
        }
    }

    private void processOnreData(DfmeOnreEntity entity) {
        // 插入元数据
        dfmeOnreMapper.insertMeta(entity);

        // 检查dflt和flightFileId是否为空
        if (entity.getDflt() == null) {
            logger.error("DFLT is null in entity");
            return;
        }
        
        String flightFileId = entity.getDflt().getFlightFileId();
        if (flightFileId == null || flightFileId.trim().isEmpty()) {
            logger.error("FLIGHT_FILE_ID is null or empty in entity");
            return;
        }
        
        logger.debug("Checking if flight exists for FLIGHT_FILE_ID: {}", flightFileId);
        
        // 插入航班基础信息，存在则跳过
        if (dfmeOnreMapper.existsFlightBase(flightFileId) == 0) {
            dfmeOnreMapper.insertFlightBase(entity);
        } else {
            logger.info("Flight base already exists for FLIGHT_FILE_ID: {}，skip insert.", flightFileId);
        }
    }
}